import copy

from PySide6.QtCore import QDateTime, Slot, Qt
from PySide6.QtWidgets import QMessageBox, QDialog, QTableWidgetItem, QMainWindow, QButtonGroup
from PySide6.QtGui import QIcon, QColor

from Devices.Chiot.BsDevs.ComDev.Forms.ComDevWindow import ComDevWindow
from Devices.Chiot.BsDevs.Switch.SwitchDevice import SwitchDevice
from Devices.Chiot.BsDevs.Switch.SwitchParser import SwitchParser
from Components.MessageBoxFunc import MessageBoxFunc
from Devices.Chiot.BsDevs.Switch.Forms.SwitchWindow_UI import Ui_FormSwitchWindow
from Devices.Chiot.BsDevs.Switch.Forms.TimerSetWindow import TimerSetWindow

class SwitchWindow(ComDevWindow):
    # 0、窗体初始化、状态变量初始化
    def __init__(self, supportDevice, parent = None):
        # 注意在实现特有设备时，一定要先将其ui对象加载完毕
        super().__init__(supportDevice, parent)

        self.FullStatus = SwitchDevice.SwitchFullStatus()

        self._ui = Ui_FormSwitchWindow()
        self._ui.setupUi(self)
        self.initUiWindow()
        self.SetupUi(self._ui)

        self.__TimerSetWindow = TimerSetWindow()

     # 1、数据解析
    def setHeartbeatStatus(self):
        #定时器
        self._ui.tableWidget_timers.clearContents()
        self._ui.tableWidget_timers.setRowCount(0)
        for timer in self.FullStatus.timers:
            if timer!= None:
                self.SetTimerToList(timer)

        #倒计时
        if 0 != self.FullStatus.delay.enable:
            self._ui.label_delayId.setText(self.FullStatus.delay.id)
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.fromSecsSinceEpoch(self.FullStatus.delay.end))
            self._ui.label_delayNotion.setVisible(False)

            switchOnoff = self.FullStatus.delay.services[0].paraValue
            self._ui.comboBox_delaySwitchCtrl.setCurrentIndex(switchOnoff)
            for srv in self.FullStatus.delay.services:
                if srv.serviceId == "switch1":
                    self._ui.radioButton_delaySwitch1Ctrl.setChecked(True)
                elif srv.serviceId == "switch2":
                    self._ui.radioButton_delaySwitch2Ctrl.setChecked(True)
                elif srv.serviceId == "switch3":
                    self._ui.radioButton_delaySwitch3Ctrl.setChecked(True)
                elif srv.serviceId == "switch4":
                    self._ui.radioButton_delaySwitch4Ctrl.setChecked(True)
                else:
                    print(__func__, "Unknown services:", srv.serviceId)
        else:
            self._ui.label_delayId.clear()
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.currentDateTime())
            self._ui.label_delayNotion.setVisible(True)
            self._ui.radioButton_delaySwitch1Ctrl.setChecked(False)
            self._ui.radioButton_delaySwitch2Ctrl.setChecked(False)
            self._ui.radioButton_delaySwitch3Ctrl.setChecked(False)
            self._ui.radioButton_delaySwitch4Ctrl.setChecked(False)

    def CmdRptStatusReceived(self, msgValue):
        if SwitchParser.ParseRptStatus(msgValue, self.FullStatus):
            self.setFullStatus()

    def CmdHeartbeatReceived(self, msgValue):
        if SwitchParser.ParseHeartbeat(msgValue, self.FullStatus):
            self.setFullStatus()
            self.setHeartbeatStatus()

    def CmdFullStatusReceived(self, msgValue):
        pass

    def CmdMsgValueReceived(self, msgName, msgValue):
        pass

    # 2、运行状态
    def setFullStatus(self):
        self._ui.label_switch1Status.setText("打开" if self.FullStatus.switch1Status else "关闭")
        self._ui.label_switch2Status.setText("打开" if self.FullStatus.switch2Status else "关闭")
        self._ui.label_switch3Status.setText("打开" if self.FullStatus.switch3Status else "关闭")
        self._ui.label_switch4Status.setText("打开" if self.FullStatus.switch4Status else "关闭")

        self._ui.radioButton_switch1Ctrl.blockSignals(True)
        self._ui.radioButton_switch2Ctrl.blockSignals(True)
        self._ui.radioButton_switch3Ctrl.blockSignals(True)
        self._ui.radioButton_switch4Ctrl.blockSignals(True)

        self._ui.radioButton_switch1Ctrl.setChecked(True if self.FullStatus.switch1Status else False)
        self._ui.radioButton_switch2Ctrl.setChecked(True if self.FullStatus.switch2Status else False)
        self._ui.radioButton_switch3Ctrl.setChecked(True if self.FullStatus.switch3Status else False)
        self._ui.radioButton_switch4Ctrl.setChecked(True if self.FullStatus.switch4Status else False)

        self._ui.radioButton_switch1Ctrl.blockSignals(False)
        self._ui.radioButton_switch2Ctrl.blockSignals(False)
        self._ui.radioButton_switch3Ctrl.blockSignals(False)
        self._ui.radioButton_switch4Ctrl.blockSignals(False)
    
    # 3、设备控制
    @Slot(bool)
    def on_radioButton_switch1Ctrl_toggled(self, checked):
        if bool(self.FullStatus.switch1Status) != checked:
            cmd = SwitchParser.PackSetAttr("switch1", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_switch2Ctrl_toggled(self, checked):
        if bool(self.FullStatus.switch2Status) != checked:
            cmd = SwitchParser.PackSetAttr("switch2", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_switch3Ctrl_toggled(self, checked):
        if bool(self.FullStatus.switch3Status) != checked:
            cmd = SwitchParser.PackSetAttr("switch3", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_switch4Ctrl_toggled(self, checked):
        if bool(self.FullStatus.switch4Status) != checked:
            cmd = SwitchParser.PackSetAttr("switch4", "on", int(checked))
            self.SendCommandText(cmd)

    # 4、定时器
    @Slot()
    def on_pushButton_addTimer_clicked(self):
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            timer = SwitchDevice.Timer()
            self.__TimerSetWindow.GetTimer(timer)
            cmd = SwitchParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)
    
    @Slot()
    def on_pushButton_delTimer_clicked(self):
        rowCount = self._ui.tableWidget_timers.currentRow()
        if rowCount >= 0:
            timer = copy.deepcopy(self.FullStatus.timers[rowCount])
            timer.week = 0
            cmd = SwitchParser.PackSetTimer(timer)
            self.SendCommandText(cmd)

    @Slot(QTableWidgetItem)
    def on_tableWidget_timers_itemDoubleClicked(self, item):
        rowCount = item.row()
        timer = copy.deepcopy(self.FullStatus.timers[rowCount])

        self.__TimerSetWindow.SetTimer(timer)
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            self.__TimerSetWindow.GetTimer(timer)
            cmd = SwitchParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_setDelay_clicked(self):
        delay = SwitchDevice.Delay()

        delay.enable = True
        delay.end = self._ui.dateTimeEdit_delayExecTime.dateTime().toSecsSinceEpoch()
        #灯开关
        delay.services.clear()
        switchOnoff = self._ui.comboBox_delaySwitchCtrl.currentIndex()
        if self._ui.radioButton_delaySwitch1Ctrl.isChecked():
            delay.services.append(SwitchDevice.ServiceParams("switch1", "on", switchOnoff))
        if self._ui.radioButton_delaySwitch2Ctrl.isChecked():
            delay.services.append(SwitchDevice.ServiceParams("switch2", "on", switchOnoff))
        if self._ui.radioButton_delaySwitch3Ctrl.isChecked():
            delay.services.append(SwitchDevice.ServiceParams("switch3", "on", switchOnoff))
        if self._ui.radioButton_delaySwitch4Ctrl.isChecked():
            delay.services.append(SwitchDevice.ServiceParams("switch4", "on", switchOnoff))
        cmd = SwitchParser.PackSetDelay(delay)
        print(cmd)
        self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_delDelay_clicked(self):
        if self.FullStatus.delay:
            delay = copy.deepcopy(self.FullStatus.delay)
            delay.enable = False
            # self._ui.dateTimeEdit_delayTime.setDateTime(QDateTime.currentDateTime())

            cmd = SwitchParser.PackSetDelay(delay)
            print(cmd)
            self.SendCommandText(cmd)

    